import { defineStore } from "pinia";
import { ref } from "vue";
import { functionTreeApi } from "@/apis/functionTreeApi";
import { useUserStore } from "@/stores/user";

export const useFunctionTreeStore = defineStore("functionTree", () => {
  // 定义管理系统功能树的state
  const functionTreeInfo = ref([]);
  // 从本地存储中加载数据
  const loadFunctionTreeInfoFromLocalStorage = async () => {
    const savedFunctionTreeInfo = JSON.parse(
      localStorage.getItem("functionTreeInfo")
    );
    //本地存在功能树
    if (savedFunctionTreeInfo) {
      functionTreeInfo.value = savedFunctionTreeInfo;
      return;
    }
    //不存在则重新获取
    const userStore = useUserStore();
    if (userStore.userInfo.token) {
      const res = await functionTreeApi();
      console.log("不存在重新获取：");
      functionTreeInfo.value = res.data;
      console.log(functionTreeInfo.value);
      if (res.data) {
        localStorage.setItem("functionTreeInfo", JSON.stringify(res.data));
      }
    }
  };

  // 在 store 创建时加载数据
  loadFunctionTreeInfoFromLocalStorage();

  // 定义获取接口数据的action函数
  const getFunctionTreeInfo = async () => {
    // 判断本地是否存有功能树信息
    if (localStorage.getItem("functionTreeInfo")) {
      console.log("本地存在功能树信息，不请求接口");
      return;
    }
    console.log("本地没有功能树信息，开始请求接口");
    const res = await functionTreeApi();
    functionTreeInfo.value = res.data;
    console.log(functionTreeInfo.value);
    // 保存数据到本地存储
    localStorage.setItem("functionTreeInfo", JSON.stringify(res.data));
  };

  // 退出登录清除信息
  const clearFunctionTreeInfo = () => {
    functionTreeInfo.value = {};
    localStorage.removeItem("functionTreeInfo");
  };

  // 返回state和actions
  return {
    functionTreeInfo,
    getFunctionTreeInfo,
    clearFunctionTreeInfo,
  };
});
